<link href="/static/webuploader-0.1.5/materialdesignicons.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/static/webuploader-0.1.5/webuploader.css" />
<!-- <link rel="stylesheet" type="text/css" href="/static/admin/css/upload.css"> -->
<link rel="stylesheet" type="text/css" href="/static/admin/css/upload2.css">
<link href="/static/webuploader-0.1.5/magnific-popup.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/static/admin/js/jquery-confirm/jquery-confirm.min.css">

<style>
    .pic-item {
        padding: 0;
        margin-right: 20px;
    }

    .big {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        display: none;
    }
</style>
<main class="lyear-layout-content">

    <div class="container-fluid p-t-15">
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div class=" callout-success callout" style="padding: 0;">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb" style="padding: 1.25rem 1rem;background-color: white;">
                            <li class="breadcrumb-item"><a href="{:url('admin/product/index')}">商品列表</a>
                            </li>
                            <li class="breadcrumb-item active" aria-current="page">商品信息修改</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">

                        <form action="" enctype="multipart/form-data" id="example-form" method="post" class="row">
                            <div class="form-group col-md-12">
                                <label for="title">商品名称</label>
                                <input type="text" class="form-control" id="name" name="name" value="{$product.name}"
                                    placeholder="请输入商品名称">
                            </div>

                            <div class="form-group col-md-12">
                                <label for="seo_keywords">商品单价</label>
                                <input type="text" class="form-control" id="price" name="price" value="{$product.price}"
                                    placeholder="商品单价">
                            </div>

                            <div class="form-group col-md-12">
                                <label for="seo_keywords">商品库存</label>
                                <input type="text" class="form-control" id="stock" name="stock" value="{$product.stock}"
                                    placeholder="商品库存,默认为0">
                            </div>

                            <div class="form-group col-md-12">
                                <label for="type">商品分类</label>
                                <div class="form-controls">
                                    <select name="typeid" class="form-control selectpicker" data-style="btn-primary"
                                        id="typeid">
                                        {foreach $TypeList as $item}
                                        <option value="{$item.id}" {$product.typeid==$item.id ? 'selected' : '' }>
                                            {$item.name}</option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group col-md-12">
                                <label for="type">商品类别</label>
                                <div class="form-controls">
                                    <select name="flag" class="form-control selectpicker" data-style="btn-primary"
                                        id="flag">
                                        {foreach $flag as $key => $val}
                                        <option value="{$key}" {$product.flag==$key ? 'selected' : '' }>{$val}</option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group col-md-12">
                                <label for="seo_description">商品描述</label>
                                <textarea class="form-control" id="content" name="content" rows="5" value=""
                                    placeholder="商品描述,其中必须以逗号分隔。如：品牌：xx,商品名称：xxx,..."
                                    style="resize: none;">{$product.content_text}</textarea>
                            </div>

                            <div class="form-group col-md-12">
                                <label>封面上传</label>
                                <div class="js-upload-image">
                                    <button class="btn btn-primary btn-w-md" type="button"
                                        onclick="upload('#cover','.cover')" style="margin-bottom: 20px;">封面上传</button>
                                    <input type="file" id="cover" name="cover" hidden="" />

                                    <ul class="list-inline row lyear-uploads-pic mb-0" style="display: flex">

                                        <li class="col-xs-6 col-sm-3 col-md-2 pic-item" id="WU_FILE_9999">
                                            <figure>
                                                <img class="cover" src="{$product.cover}">
                                                <figcaption>
                                                    <a class="btn btn-round btn-square btn-primary btn-link-pic WU_FILE_9999"
                                                        href="{$product.cover}"><i class="mdi mdi-eye"></i></a>
                                                </figcaption>
                                            </figure>
                                        </li>

                                    </ul>
                                </div>
                            </div>

                            <div class="form-group col-md-12">
                                <label>多图片上传</label>

                                <div class="js-upload-image">
                                    <input type="hidden" name="more_pic" data-multiple="true" data-size="2048000"
                                        data-ext="gif,jpg,jpeg,bmp,png" id="more_pic" value="" />
                                    <div id="picker_more_pic">上传多张图片</div>
                                    <!--ul用来存放图片预览-->
                                    <ul id="file_list_more_pic" class="list-inline clearfix lyear-uploads-pic"
                                        style="display: flex">
                                        {foreach $product.thumbs_list as $key => $val}
                                        <li class="col-xs-6 col-sm-3 col-md-2 pic-item" id="{$key+1}">
                                            <figure>
                                                <img src="{$val}" />
                                                <figcaption>
                                                    <a class="btn btn-round btn-square btn-primary btn-link-pic"
                                                        data-id="{$key+1}" href="{$val}"><i class="mdi mdi-eye"></i></a>
                                                    <a class="btn btn-round btn-square btn-danger btn-remove-pic"
                                                        href="#!"><i class="mdi mdi-delete"></i></a>
                                                </figcaption>
                                            </figure>
                                        </li>
                                        {/foreach}
                                    </ul>
                                </div>
                                <input type="hidden" id="thumbs" name="thumbs" value="" />
                            </div>

                            <div class="form-group col-md-12">
                                <button type="submit" class="btn btn-primary ajax-post"
                                    target-form="add-form">更新</button>
                                <button type="button" class="btn btn-default"
                                    onclick="javascript:history.back(-1);return false;">返 回</button>
                            </div>
                        </form>

                    </div>
                </div>
            </div>

        </div>
    </div>

</main>

<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/webuploader-0.1.5/webuploader.min.js"></script>
<script type="text/javascript" src="/static/webuploader-0.1.5/jquery.magnific-popup.min.js"></script>
<script type="text/javascript" src="/static/admin/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery-confirm/jquery-confirm.min.js"></script>
<script>
    var thumbs = '';
    let nums = 0;
    // 图片预览函数
    function GetObjectURL(file) {
        // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
        var url = null;

        //判断是否为IE浏览器还是google还是其他浏览器
        if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file)
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file)
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file)
        }

        return url
    }

    function upload(elem, img) {
        // 点击拉起上传选择
        $(elem).click()

        $(elem).change(function () {
            let file = $(this)[0].files[0] ? $(this)[0].files[0] : {}

            let url = GetObjectURL(file);

            $(img).attr("src", url);
            $('.cover').attr("src", url)
            $('.WU_FILE_9999').attr("href", url)

        })
    }
</script>
<script>
    var thumbArr = "";

    /*
     * 示例上传成功采用返回ID的形式，即上传成功以附件表形式存储，返回给前端ID值。
     * 成功返回示例：{"status":200,"info":"成功","class":"success","id":1,"picurl":".\/upload\/images\/lyear_5ddfc00174bbb.jpg"}
     * 这里设定单图上传为js-upload-image，多图上传为js-upload-images
     * 存放预览图的div元素，命名：file_list_*；后面的上传按钮的命名：filePicker_*（这里的*跟隐藏的input的name对应）。方便单页面中存在有多个上传时区分以及使用。
     * input上保存上传后的图片ID以及设置上传时的一些参数，
     */

    // 通用绑定，
    $(".js-upload-image,.js-upload-images").each(function () {
        var $input_file = $(this).find("input"),
            $input_file_name = $input_file.attr("name"),
            $multiple = $input_file.data("multiple"), // 是否选择多个文件
            $ext = $input_file.data("ext"), // 支持的文件后缀，示例以图片为例
            $size = $input_file.data("size"); // 支持最大的文件大小
        var $file_list = $("#file_list_" + $input_file_name);
        var ratio = window.devicePixelRatio || 1;
        var thumbnailWidth = 220 * ratio;
        var thumbnailHeight = 220 * ratio;

        var uploader = WebUploader.create({
            auto: true,
            duplicate: true,
            resize: false,
            swf: "/static/webuploader-0.1.5/Uploader.swf",
            server: `{:url('admin/product/uploads')}`,
            pick: {
                id: "#picker_" + $input_file_name,
                multiple: $multiple,
            },
            fileSingleSizeLimit: $size,
            accept: {
                title: "Images",
                extensions: $ext,
                mimeTypes: "image/*",
            },
        });

        uploader.on("fileQueued", function (file) {
            var $li = $(
                    '<li class="col-xs-6 col-sm-3 col-md-2 pic-item" id="' +
                    file.id +
                    '">' +
                    "  <figure>" +
                    "    <img>" +
                    "    <figcaption>" +
                    '      <a class="btn btn-round btn-square btn-primary btn-link-pic" href="#!"><i class="mdi mdi-eye"></i></a>' +
                    '      <a class="btn btn-round btn-square btn-danger btn-remove-pic" href="#!"><i class="mdi mdi-delete"></i></a>' +
                    "    </figcaption>" +
                    "  </figure>" +
                    "</li>"
                ),
                $img = $li.find("img");

            if ($multiple) {
                $file_list.append($li);
            } else {
                $file_list.html($li);
                $input_file.val("");
            }
            uploader.makeThumb(
                file,
                function (error, src) {
                    if (error) {
                        $img.replaceWith("<span>不能预览</span>");
                        return;
                    }
                    $img.attr("src", src);
                },
                thumbnailWidth,
                thumbnailHeight
            );
            $(
                '<div class="progress progress-sm"><div class="progress-bar progress-bar-primary progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div></div>'
            ).appendTo($li);
        });
        uploader.on("uploadProgress", function (file, percentage) {
            var $percent = $("#" + file.id).find(".progress-bar");
            $percent.css("width", percentage * 100 + "%");
        });
        uploader.on("uploadSuccess", function (file, response) {
            var $li = $("#" + file.id);

            if (response.status == 200) {
                // 返回200成功
                thumbArr += response.picurl + ",";
                console.log(thumbArr);
                $("#thumbs").val(thumbArr);

                if ($multiple) {
                    if ($input_file.val()) {
                        $input_file.val($input_file.val() + "," + response.id);
                    } else {
                        $input_file.val(response.id);
                    }
                    $li.find(".btn-remove-pic").attr("data-id", response.id);
                } else {
                    $input_file.val(response.id);
                }
            }
            $('<div class="' + response.class + '"></div>')
                .text(response.info)
                .appendTo($li);
            $li.find("a.btn-link-pic").attr("href", response.picurl);

            $li.data("id", response.id);
            console.log($li.data("id"));
        });
        uploader.on("uploadError", function (file) {
            var $li = $("#" + file.id);
            $('<div class="error">上传失败</div>').appendTo($li);
        });
        uploader.on("error", function (type) {
            switch (type) {
                case "Q_TYPE_DENIED":
                    alert(
                        "图片类型不正确，只允许上传后缀名为：" + $ext + "，请重新上传！"
                    );
                    //lightyear.notify('图片类型不正确，只允许上传后缀名为：' + $ext + '，请重新上传！', 'danger');
                    break;
                case "F_EXCEED_SIZE":
                    alert("图片不得超过" + $size / 1024 + "kb，请重新上传！");
                    //lightyear.notify('图片不得超过' + ($size / 1024) + 'kb，请重新上传！', 'danger');
                    break;
            }
        });
        uploader.on("uploadComplete", function (file) {
            setTimeout(function () {
                $("#" + file.id)
                    .find(".progress")
                    .remove();
            }, 500);
        });
        // 删除操作 防止追加元素无法触发事件
        $file_list.delegate(".btn-remove-pic", "click", function () {
            $.confirm({
                title: "提示",
                escapeKey: true,
                content: "你确认要删除该图片吗",
                backgroundDismiss: true,
                theme: 'modern',
                type: 'red',
                icon: 'mdi mdi-alert-outline mdi-36px',
                buttons: {
                    okay: {
                        text: "确认",
                        keys: ["enter"],
                        btnClass: 'btn-info',
                        action: () => {
                            // 可改为对话框插件
                            if ($multiple) {
                                var id = $(this).data("id"),
                                    ids = $input_file.val().split(",");
                                if (id) {
                                    for (var i = 0; i < ids.length; i++) {
                                        if (ids[i] == id) {
                                            ids.splice(i, 1);
                                            break;
                                        }
                                    }
                                    $input_file.val(ids.join(","));
                                }
                            } else {
                                $input_file.val("");
                            }

                            // TODO 发起ajax请求删除图片
                            let url = $(this).siblings(".btn-link-pic").attr("href");
                            // console.log(url);
                            $.ajax({
                                type: "post",
                                url: `{:url('admin/product/del_img')}`,
                                data: {
                                    url,
                                },
                                dataType: "json",
                                success: (res) => {
                                    console.log(res);
                                    if (res.code === 1) {
                                        $.notify({
                                            icon: "mdi mdi-check",
                                            message: res.msg,
                                        }, {
                                            type: "success",
                                            delay: 1000,
                                            onClose: () => {
                                                $(this).closest(
                                                        ".pic-item")
                                                    .remove();
                                            },
                                        });
                                    } else {
                                        $.notify({
                                            icon: 'mdi mdi-window-close',
                                            message: res.msg,
                                        }, {
                                            type: "danger",
                                        });
                                    }
                                },
                            });
                        },
                    },
                    cancel: {
                        text: "取消",
                        keys: ["ctrl", "shift"],
                        btnClass: 'btn-danger'
                    },
                },
            });

        });
        // 接入图片查看插件
        $(this).magnificPopup({
            delegate: "a.btn-link-pic",
            type: "image",
            gallery: {
                enabled: true,
            },
        });
    });
</script>